package common

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"gopkg.in/ini.v1"
	"log"
	"strconv"
	"time"
)

func InitDB() *gorm.DB {

	conf, _ := ini.Load("./conf/ginweb.ini")

	driverName := "mysql"
	host := conf.Section("mysql").Key("host").String()
	port := conf.Section("mysql").Key("port").String()
	database := conf.Section("mysql").Key("databases").String()
	username := conf.Section("mysql").Key("user").String()
	password := conf.Section("mysql").Key("passwd").String()
	charset := "utf8"
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset,
	)

	db, err := gorm.Open(driverName, args)
	//db, err := gorm.Open("mysql", "user:islot@/blog?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	return db

}

var (
	Redis *redis.Client
)

func getRedis() {

	if Redis == nil {

		conf, _ := ini.Load("./conf/ginweb.ini")

		addr := conf.Section("redis").Key("host").String() + ":" + conf.Section("redis").Key("port").String()
		pwd := conf.Section("redis").Key("passwd").String()

		if len(pwd) < 1 {
			Redis = redis.NewClient(&redis.Options{
				Addr: addr,
			})
		} else {
			Redis = redis.NewClient(&redis.Options{
				Addr:     addr,
				Password: pwd,
			})
		}

	}
}

func ReturnMsg(code int, sta int, msg string, c *gin.Context) {
	c.JSON(code, gin.H{
		"sta": sta,
		"msg": msg,
	})

}

func SetMd5(str string) string {
	m := md5.New()
	m.Write([]byte(str))
	return hex.EncodeToString(m.Sum(nil))

}

type LoginSession struct {
	Id        int    `json:"id"`
	Uname     string `json:"uname"`
	Status    int    `json:"status"`
	LastLogin int    `json:"last_login"`
}

func SetLogin(info *LoginSession) bool {

	session := LoginSession{info.Id, info.Uname, info.Status, info.LastLogin}
	jsonStr, _ := json.Marshal(session)

	getRedis()

	err := Redis.Set("login_session_"+strconv.Itoa(info.Id), string(jsonStr), time.Duration(900)*time.Second).Err()

	if err != nil {
		log.Println("set session fail")
		log.Println("%v", err)
		return false
	}
	return true

}

func CheckLogin(c *gin.Context) bool {

	id, err := c.Cookie("test")
	if err != nil {
		return false
	}

	if id == "" {
		return false
	}

	getRedis()

	session := Redis.Get("login_session_" + id)

	if session == nil {
		return false
	}

	//续命
	Redis.Expire("login_session_"+id, time.Duration(900)*time.Second)

	return true
}

func SetCookie(c *gin.Context, id int) {
	c.SetCookie("test", strconv.Itoa(id), 0, "/", "", false, true)
}

func LoginOut(c *gin.Context) bool {

	id, err := c.Cookie("test")
	if err != nil {
		return true
	}

	if id == "" {
		return true
	}

	getRedis()

	Redis.Del("login_session_" + id)

	c.SetCookie("test", "", -1, "/", "", false, true)

	return true
}
